package com.qujia.station.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 接口幂等工具类
 * 使用redis实现
 */
@Component
public class IdempotentUtil {

    //key过期时间，单位秒
    public static final int EXPIRE_SECOND = 1800;
    public static final String KEY_PREFIX = "userCode:";

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    public boolean tryLock(String key){
        return tryLock(key,EXPIRE_SECOND);
    }

    public boolean tryLockUser(String key){
        return tryLock(key,EXPIRE_SECOND);
    }


    /**
     *
     * @param key key
     * @param expire 过期时间，单位秒
     * @return
     */
    public boolean tryLock(String key, int expire){
        long now = System.currentTimeMillis();
        Boolean b = redisTemplate.opsForValue().setIfAbsent(key, String.valueOf(now), expire, TimeUnit.SECONDS);
        return b != null && b;
    }

    public void releaseLock(String key){
        redisTemplate.delete(key);
    }

    public static String GenerateKey(String... strings){
        StringBuilder builder = new StringBuilder(KEY_PREFIX);
        for (String string : strings) {
            builder.append(string);
        }
        return builder.toString();
    }

}
